//
//  WSGInfiniteScrollView.m
//  oneDollar
//
//  Created by Laki on 16/6/16.
//  Copyright © 2016年 com.Laki.corder. All rights reserved.
//

#import "WSGInfiniteScrollView.h"
#import "WSGInfiniteCell.h"
#import "WSGAdInfosItem.h"

#import <UIImageView+WebCache.h>

@interface WSGInfiniteScrollView()<UICollectionViewDataSource,UICollectionViewDelegate>
/** 定时器*/
@property (nonatomic, weak) NSTimer *timer;
/** UICollectionView*/
@property (nonatomic, weak) UICollectionView *collectionView;
@end

@implementation WSGInfiniteScrollView
/** 初始数*/
static NSInteger WSGItemCount = 20;
/** 重用标识符*/
static NSString * const WSGImageCellId = @"WSGInfiniteCell";

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 创建流水布局
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        // 设置滑动方向
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        // 设置间距
        layout.minimumLineSpacing = 0;
        
        // 创建UICollectionView
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        
        // 设置数据源
        collectionView.dataSource = self;
        // 设置代理
        collectionView.delegate = self;
        // 开启分页
        collectionView.pagingEnabled = YES;
        // 隐藏滚动条
        collectionView.showsHorizontalScrollIndicator = NO;
        collectionView.showsVerticalScrollIndicator = NO;
        
        // 注册UICollectionViewCell
        [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([WSGInfiniteCell class]) bundle:nil] forCellWithReuseIdentifier:WSGImageCellId];
        
        // 添加到视图中
        [self addSubview:collectionView];
        
        // 设置全局
        self.collectionView = collectionView;
    }
    return self;
}

/*
 * 布局子控件的位置
 */
- (void)layoutSubviews
{
    [super layoutSubviews];
    // 设置UICollectionView的Frame
    self.collectionView.frame = self.bounds;
    
    // 设置流水布局的Frame
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    layout.itemSize = self.bounds.size;
}

#pragma mark --------------------
#pragma mark 根据模型设置数据
- (void)setAdinfosItemM:(NSArray *)adinfosItemM{
    _adinfosItemM = adinfosItemM;
    
    // 一开始先设置显示的Cell为最中间的数
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:(WSGItemCount * self.adinfosItemM.count) / 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    
    // 开启定时器
    [self startTimer];
}

#pragma mark --------------------
#pragma mark 定时器
/*
 * 开启定时器
 */
- (void)startTimer
{
    // 创建定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    
    // 加入RunLoop中
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

/*
 * 停止定时器
 */
- (void)stopTimer
{
    // 关闭定时器
    [self.timer invalidate];
    
    // 清空指针
    self.timer = nil;
}

/*
 * 偏移到下一个图片
 */
- (void)nextPage
{
    // 取出偏移量
    CGPoint offset = self.collectionView.contentOffset;
    
    // 加上一张图片的宽度
    offset.x += self.bounds.size.width;
    
    // 偏移
    [self.collectionView setContentOffset:offset animated:YES];
}

#pragma mark --------------------
#pragma mark UICollectionViewDataSource
/*
 * 显示多少个Cell
 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return WSGItemCount * self.adinfosItemM.count;
}

/*
 * 每个Cell中的数据
 */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 从缓存池中取出WSGInfiniteCell
    WSGInfiniteCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:WSGImageCellId forIndexPath:indexPath];
    
    // 取出当前模型
    WSGAdInfosItem *item = self.adinfosItemM[indexPath.item % self.adinfosItemM.count];

    // 设置图片
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:item.picture] placeholderImage:[UIImage imageNamed:@"Circle_BackgroundBigImage"]];
    
    return cell;
}

#pragma mark --------------------
#pragma mark 其他
- (void)resetPosition
{
    // 计算出当前是第几张图片
    NSInteger oldItem = self.collectionView.contentOffset.x / self.bounds.size.width;
    
    // 需要滚动到第几张图片(无线轮播器的核心)
    NSInteger newItem = (WSGItemCount * self.adinfosItemM.count / 2) + (oldItem % self.adinfosItemM.count);
    
    // 滚动到哪张图片
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:newItem inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}

#pragma mark --------------------
#pragma mark UICollectionViewDelegate
/*
 * 人为开始拖动ScrollView时调用
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];
}

/*
 * 人为停止拖动ScrolLView时调用
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self startTimer];
}

/*
 * ScrollView滚动完毕时调用(通过setContentOffset:animated:滚动)
 */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self resetPosition];
}

/*
 * ScrollView滚动完毕时调用(人为滚动)
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self resetPosition];
}

/*
 * 选中某行Cell调用
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    // 取出对应的模型数据
    WSGAdInfosItem *item = self.adinfosItemM[indexPath.item % self.adinfosItemM.count];
    
    // 调用代理方法
    if ([self.delegate respondsToSelector:@selector(infiniteScrollView:url:)]) {
        [self.delegate infiniteScrollView:self url:item.clickUrl];
    }
}
@end
